package com.bh.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Wang
 * @version 1.0
 * @date 2022/6/9 13:58
 */
public class TokenFilter extends ZuulFilter {
    @Override
    public String filterType() {        //请求前过滤
        return "pre";
    }

    @Override
    public int filterOrder() {      //过滤器执行顺序
        return 0;
    }

    @Override
    public boolean shouldFilter() {     //执行该过滤器
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext=RequestContext.getCurrentContext();
        HttpServletRequest request=requestContext.getRequest();
        String token=request.getHeader("x-token");
        if (null==token){   //说明无权访问
            requestContext.setSendZuulResponse(false);      //停止想服务发送请求
            requestContext.getResponse().setContentType("application/json;charset=utf-8");      //设置网关影响客户端的内容
            requestContext.setResponseBody("{code:0,msg:'无权访问'}");
        }

        requestContext.set("token",token);
        return null;
    }

}
